package com.car.json;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.car.util.ConnectionPool;
import com.car.util.DocUtil;
import com.sun.corba.se.spi.orbutil.fsm.Guard.Result;

//得到太平洋的汽车的bbsid
public class PCAutoBBSID {
	Connection conn = ConnectionPool.getConnection("carvoice_core", "root", "zhouzhou100428", "carvoice.tpddns.cn");

	public List<Integer> getID() {
		List<Integer> list = new ArrayList<>();

		Statement st = null;
		ResultSet rs = null;
		String sql = "SELECT pcauto_id FROM core_brand_pcauto";
		try {
			st = conn.createStatement();
			rs = st.executeQuery(sql);
			while (rs.next()) {
				int id = rs.getInt("pcauto_id");
				list.add(id);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
	}

	public List<Integer> getBBSID(int id) {
		List<Integer> list = new ArrayList<>();
		try {
			Elements carList = null;
			Document doc = DocUtil.getDoc("http://price.pcauto.com.cn/sg" + id + "/");
			carList = doc.select("ul.channel li a:contains(论坛)");
			for (Element e : carList) {
				int bbsid = e.attr("href").split("-").length > 1
						? Integer.parseInt(e.attr("href").split("-")[1].split("\\.")[0]) : 0;
				updateBBSID(id, bbsid);
			}
		} catch (Exception e1) {
			System.out.println(id);
		}

		return list;
	}

	public void updateBBSID(int id, int bbsid) {
		Statement st = null;
		String sql = "UPDATE core_brand_pcauto SET pcauto_bbsid=" + bbsid + " WHERE pcauto_id=" + id;
		try {
			st = conn.createStatement();
			st.executeUpdate(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		PCAutoBBSID p = new PCAutoBBSID();
		List<Integer> list = p.getID();
		if (list != null) {
			for (Integer i : list) {
				p.getBBSID(i);
			}
		}
	}
}
